package de.hs.rm.UJAdapter.impl;

import java.util.Dictionary;
import java.util.Hashtable;

import org.osgi.framework.BundleContext;
import org.osgi.framework.Filter;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.service.upnp.*;

public class UJDevice implements UPnPDevice, UPnPEventListener, ServiceListener{

	private Dictionary props = null;
	private UPnPService[] services = null;
	private UPnPIcon[] icons = null;
	private BundleContext bundleContext = null;
	
	public UJDevice()
	{
		icons = new UJIconImpl[]{new UJIconImpl(32, 32, 256, 143,
                "image/gif", "osgiupnpprinter.gif")};
	}
	
	@Override
	public UPnPService getService(String serviceId) {
		for (int i=0; i<services.length; i++)
			if (services[i].getId().equals(serviceId))
		        return services[i];
		return null;
	}

	@Override
	public UPnPService[] getServices() {
		return services;
	}
	
	public void setServices(UPnPService[] services)
	{
		this.services = services.clone();
		
	}

	@Override
	public UPnPIcon[] getIcons(String locale) {
		return icons;
	}

	@Override
	public Dictionary getDescriptions(String locale) {
		return props;
	}
	
	public void setDescriptions(Dictionary props)
	{
		this.props = props;
	}
	
	public static String getLocalHostname() {
		try {
			return java.net.InetAddress.getLocalHost().getHostName();
	    } catch (Exception uhe) {
	    	return "unknown IP";
	    }
	}
	
	public void generateEvent(Dictionary matchDictionary, Dictionary events) throws Exception
    {
		 // get all UPnPEventListener listeners from the registry of the OSGi framework. 
		 ServiceReference listeners[] = 
				 bundleContext.getServiceReferences(UPnPEventListener.class.getName(), null);
		 if(listeners != null)
		 {
			 for (int i=0; i<listeners.length; i++)
			 {
				 // get listener filter         
				 Filter filter = (Filter) listeners[i].getProperty(UPnPEventListener.UPNP_FILTER); 
				 // evaluate filter
				 if (filter.match(matchDictionary))
				 {
				 		//if(listeners[i] instanceof UPnPEventListener)
				 		UPnPEventListener upnpListener = (UPnPEventListener) bundleContext.getService(listeners[i]);
				 		upnpListener.notifyUPnPEvent(
				                              (String) matchDictionary.get(UPnPDevice.UDN),
				                              (String) matchDictionary.get(UPnPService.ID), 
				                               events);        
				 }
			 }
		 }
	}

	public BundleContext getBundleContext() {
		return bundleContext;
	}

	public void setBundleContext(BundleContext bundleContext) {
		this.bundleContext = bundleContext;
	}

	@Override
	public void notifyUPnPEvent(String deviceId, String serviceId,
			Dictionary events) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void serviceChanged(ServiceEvent event) {
		// TODO Auto-generated method stub
		
	}

}
